[[...path]].page.tsx 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476
  1. import React, { useEffect } from 'react';
  2. import { isClient, pagePathUtils, pathUtils } from '@growi/core';
  3. import ExtensibleCustomError from 'extensible-custom-error';
  4. import {
  5. NextPage, GetServerSideProps, GetServerSidePropsContext,
  6. } from 'next';
  7. import { serverSideTranslations } from 'next-i18next/serverSideTranslations';
  8. import dynamic from 'next/dynamic';
  9. import Head from 'next/head';
  10. import { useRouter } from 'next/router';
  11. import { PageAlerts } from '~/components/PageAlert/PageAlerts';
  12. // import { PageComments } from '~/components/PageComment/PageComments';
  13. // import { useTranslation } from '~/i18n';
  14. import { CrowiRequest } from '~/interfaces/crowi-request';
  15. // import { renderScriptTagByName, renderHighlightJsStyleTag } from '~/service/cdn-resources-loader';
  16. // import { useIndentSize } from '~/stores/editor';
  17. // import { useRendererSettings } from '~/stores/renderer';
  18. // import { EditorMode, useEditorMode, useIsMobile } from '~/stores/ui';
  19. import { IPageWithMeta } from '~/interfaces/page';
  20. import { ISidebarConfig } from '~/interfaces/sidebar-config';
  21. import { PageModel, PageDocument } from '~/server/models/page';
  22. import UserUISettings, { UserUISettingsDocument } from '~/server/models/user-ui-settings';
  23. import Xss from '~/services/xss';
  24. import { useSWRxCurrentPage, useSWRxPageInfo, useSWRxPage } from '~/stores/page';
  25. import {
  26. usePreferDrawerModeByUser, usePreferDrawerModeOnEditByUser, useSidebarCollapsed, useCurrentSidebarContents, useCurrentProductNavWidth,
  27. } from '~/stores/ui';
  28. import loggerFactory from '~/utils/logger';
  29. // import { isUserPage, isTrashPage, isSharedPage } from '~/utils/path-utils';
  30. // import GrowiSubNavigation from '../client/js/components/Navbar/GrowiSubNavigation';
  31. // import GrowiSubNavigationSwitcher from '../client/js/components/Navbar/GrowiSubNavigationSwitcher';
  32. import { BasicLayout } from '../components/BasicLayout';
  33. import DisplaySwitcher from '../components/Page/DisplaySwitcher';
  34. // import { serializeUserSecurely } from '../server/models/serializers/user-serializer';
  35. // import PageStatusAlert from '../client/js/components/PageStatusAlert';
  36. import {
  37. useCurrentUser, useCurrentPagePath,
  38. useOwnerOfCurrentPage, useIsLatestRevision,
  39. useIsForbidden, useIsNotFound, useIsTrashPage, useShared, useShareLinkId, useIsSharedUser, useIsAbleToDeleteCompletely,
  40. useAppTitle, useSiteUrl, useConfidential, useIsEnabledStaleNotification,
  41. useIsSearchServiceConfigured, useIsSearchServiceReachable, useIsMailerSetup,
  42. useAclEnabled, useIsAclEnabled, useHasSlackConfig, useDrawioUri, useHackmdUri, useMathJax,
  43. useNoCdn, useEditorConfig, useCsrfToken, useIsSearchScopeChildrenAsDefault, useCurrentPageId, useCurrentPathname, useIsSlackConfigured,
  44. } from '../stores/context';
  45. import { useXss } from '../stores/xss';
  46. import {
  47. CommonProps, getNextI18NextConfig, getServerSideCommonProps, useCustomTitle,
  48. } from './commons';
  49. // import { useCurrentPageSWR } from '../stores/page';
  50. const logger = loggerFactory('growi:pages:all');
  51. const { isPermalink: _isPermalink, isUsersHomePage, isTrashPage: _isTrashPage } = pagePathUtils;
  52. const { removeHeadingSlash } = pathUtils;
  53. const IdenticalPathPage = (): JSX.Element => {
  54. const IdenticalPathPage = dynamic(() => import('../components/IdenticalPathPage').then(mod => mod.IdenticalPathPage), { ssr: false });
  55. return <IdenticalPathPage />;
  56. };
  57. type Props = CommonProps & {
  58. currentUser: string,
  59. pageWithMetaStr: string,
  60. // pageUser?: any,
  61. // redirectTo?: string;
  62. // redirectFrom?: string;
  63. // shareLinkId?: string;
  64. isLatestRevision?: boolean
  65. isIdenticalPathPage?: boolean,
  66. isForbidden: boolean,
  67. isNotFound: boolean,
  68. // isAbleToDeleteCompletely: boolean,
  69. isSearchServiceConfigured: boolean,
  70. isSearchServiceReachable: boolean,
  71. isSearchScopeChildrenAsDefault: boolean,
  72. isSlackConfigured: boolean,
  73. // isMailerSetup: boolean,
  74. isAclEnabled: boolean,
  75. // hasSlackConfig: boolean,
  76. // drawioUri: string,
  77. // hackmdUri: string,
  78. // mathJax: string,
  79. // noCdn: string,
  80. // highlightJsStyle: string,
  81. // isAllReplyShown: boolean,
  82. // isContainerFluid: boolean,
  83. // editorConfig: any,
  84. isEnabledStaleNotification: boolean,
  85. // isEnabledLinebreaks: boolean,
  86. // isEnabledLinebreaksInComments: boolean,
  87. // adminPreferredIndentSize: number,
  88. // isIndentSizeForced: boolean,
  89. // UI
  90. userUISettings: UserUISettingsDocument | null
  91. // Sidebar
  92. sidebarConfig: ISidebarConfig,
  93. };
  94. const GrowiPage: NextPage<Props> = (props: Props) => {
  95. // const { t } = useTranslation();
  96. const router = useRouter();
  97. const UnsavedAlertDialog = dynamic(() => import('./UnsavedAlertDialog'), { ssr: false });
  98. const { data: currentUser } = useCurrentUser(props.currentUser != null ? JSON.parse(props.currentUser) : null);
  99. // commons
  100. useAppTitle(props.appTitle);
  101. useSiteUrl(props.siteUrl);
  102. useXss(new Xss());
  103. // useEditorConfig(props.editorConfig);
  104. useConfidential(props.confidential);
  105. useCsrfToken(props.csrfToken);
  106. // UserUISettings
  107. usePreferDrawerModeByUser(props.userUISettings?.preferDrawerModeByUser ?? props.sidebarConfig.isSidebarDrawerMode);
  108. usePreferDrawerModeOnEditByUser(props.userUISettings?.preferDrawerModeOnEditByUser);
  109. useSidebarCollapsed(props.userUISettings?.isSidebarCollapsed ?? props.sidebarConfig.isSidebarClosedAtDockMode);
  110. useCurrentSidebarContents(props.userUISettings?.currentSidebarContents);
  111. useCurrentProductNavWidth(props.userUISettings?.currentProductNavWidth);
  112. // page
  113. useCurrentPagePath(props.currentPathname);
  114. useIsLatestRevision(props.isLatestRevision);
  115. // useOwnerOfCurrentPage(props.pageUser != null ? JSON.parse(props.pageUser) : null);
  116. useIsForbidden(props.isForbidden);
  117. useIsNotFound(props.isNotFound);
  118. // useIsTrashPage(_isTrashPage(props.currentPagePath));
  119. // useShared();
  120. // useShareLinkId(props.shareLinkId);
  121. // useIsAbleToDeleteCompletely(props.isAbleToDeleteCompletely);
  122. useIsSharedUser(false); // this page cann't be routed for '/share'
  123. useIsEnabledStaleNotification(props.isEnabledStaleNotification);
  124. useIsSearchServiceConfigured(props.isSearchServiceConfigured);
  125. useIsSearchServiceReachable(props.isSearchServiceReachable);
  126. useIsSearchScopeChildrenAsDefault(props.isSearchScopeChildrenAsDefault);
  127. useIsSlackConfigured(props.isSlackConfigured);
  128. // useIsMailerSetup(props.isMailerSetup);
  129. useIsAclEnabled(props.isAclEnabled);
  130. // useHasSlackConfig(props.hasSlackConfig);
  131. // useDrawioUri(props.drawioUri);
  132. // useHackmdUri(props.hackmdUri);
  133. // useMathJax(props.mathJax);
  134. // useNoCdn(props.noCdn);
  135. // useIndentSize(props.adminPreferredIndentSize);
  136. // useRendererSettings({
  137. // isEnabledLinebreaks: props.isEnabledLinebreaks,
  138. // isEnabledLinebreaksInComments: props.isEnabledLinebreaksInComments,
  139. // adminPreferredIndentSize: props.adminPreferredIndentSize,
  140. // isIndentSizeForced: props.isIndentSizeForced,
  141. // });
  142. // const { data: editorMode } = useEditorMode();
  143. let pageWithMeta: IPageWithMeta | undefined;
  144. if (props.pageWithMetaStr != null) {
  145. pageWithMeta = JSON.parse(props.pageWithMetaStr) as IPageWithMeta;
  146. }
  147. useCurrentPageId(pageWithMeta?.data._id);
  148. useSWRxCurrentPage(undefined, pageWithMeta?.data); // store initial data
  149. // useSWRxPage(pageWithMeta?.data._id);
  150. useSWRxPageInfo(pageWithMeta?.data._id, undefined, pageWithMeta?.meta); // store initial data
  151. useIsTrashPage(_isTrashPage(pageWithMeta?.data.path ?? ''));
  152. useCurrentPagePath(pageWithMeta?.data.path);
  153. useCurrentPathname(props.currentPathname);
  154. // sync pathname by Shallow Routing https://nextjs.org/docs/routing/shallow-routing
  155. useEffect(() => {
  156. if (isClient() && window.location.pathname !== props.currentPathname) {
  157. router.replace(props.currentPathname, undefined, { shallow: true });
  158. }
  159. }, [props.currentPathname, router]);
  160. const classNames: string[] = [];
  161. // switch (editorMode) {
  162. // case EditorMode.Editor:
  163. // classNames.push('on-edit', 'builtin-editor');
  164. // break;
  165. // case EditorMode.HackMD:
  166. // classNames.push('on-edit', 'hackmd');
  167. // break;
  168. // }
  169. // if (props.isContainerFluid) {
  170. // classNames.push('growi-layout-fluid');
  171. // }
  172. // if (page == null) {
  173. // classNames.push('not-found-page');
  174. // }
  175. return (
  176. <>
  177. <Head>
  178. {/*
  179. {renderScriptTagByName('drawio-viewer')}
  180. {renderScriptTagByName('mathjax')}
  181. {renderScriptTagByName('highlight-addons')}
  182. {renderHighlightJsStyleTag(props.highlightJsStyle)}
  183. */}
  184. </Head>
  185. {/* <BasicLayout title={useCustomTitle(props, t('GROWI'))} className={classNames.join(' ')}> */}
  186. <BasicLayout title={useCustomTitle(props, 'GROWI')} className={classNames.join(' ')}>
  187. <header className="py-0">
  188. {/* <GrowiSubNavigation /> */}
  189. GrowiSubNavigation
  190. </header>
  191. <div className="d-edit-none">
  192. {/* <GrowiSubNavigationSwitcher /> */}
  193. GrowiSubNavigationSwitcher
  194. </div>
  195. <div id="grw-subnav-sticky-trigger" className="sticky-top"></div>
  196. <div id="grw-fav-sticky-trigger" className="sticky-top"></div>
  197. <div id="main" className={`main ${isUsersHomePage(props.currentPathname) && 'user-page'}`}>
  198. <div className="row">
  199. <div className="col">
  200. <div id="content-main" className="content-main grw-container-convertible">
  201. { props.isIdenticalPathPage && <IdenticalPathPage /> }
  202. { !props.isIdenticalPathPage && (
  203. <>
  204. <PageAlerts />
  205. { props.isForbidden
  206. ? <>ForbiddenPage</>
  207. : <DisplaySwitcher />
  208. }
  209. <div id="page-editor-navbar-bottom-container" className="d-none d-edit-block"></div>
  210. {/* <PageStatusAlert /> */}
  211. PageStatusAlert
  212. </>
  213. ) }
  214. </div>
  215. </div>
  216. {/* <div className="col-xl-2 col-lg-3 d-none d-lg-block revision-toc-container">
  217. <div id="revision-toc" className="revision-toc mt-3 sps sps--abv" data-sps-offset="123">
  218. <div id="revision-toc-content" className="revision-toc-content"></div>
  219. </div>
  220. </div> */}
  221. </div>
  222. </div>
  223. <footer>
  224. {/* <PageComments /> */}
  225. PageComments
  226. </footer>
  227. <UnsavedAlertDialog />
  228. </BasicLayout>
  229. </>
  230. );
  231. };
  232. function getPageIdFromPathname(currentPathname: string): string | null {
  233. return _isPermalink(currentPathname) ? removeHeadingSlash(currentPathname) : null;
  234. }
  235. class MultiplePagesHitsError extends ExtensibleCustomError {
  236. pagePath: string;
  237. constructor(pagePath: string) {
  238. super(`MultiplePagesHitsError occured by '${pagePath}'`);
  239. this.pagePath = pagePath;
  240. }
  241. }
  242. async function getPageData(context: GetServerSidePropsContext, props: Props): Promise<IPageWithMeta|null> {
  243. const req: CrowiRequest = context.req as CrowiRequest;
  244. const { crowi } = req;
  245. const { revisionId } = req.query;
  246. const Page = crowi.model('Page') as PageModel;
  247. const { pageService } = crowi;
  248. const { currentPathname } = props;
  249. const pageId = getPageIdFromPathname(currentPathname);
  250. const isPermalink = _isPermalink(currentPathname);
  251. const { user } = req;
  252. // check whether the specified page path hits to multiple pages
  253. if (!isPermalink) {
  254. const count = await Page.countByPathAndViewer(currentPathname, user, null, true);
  255. if (count > 1) {
  256. throw new MultiplePagesHitsError(currentPathname);
  257. }
  258. }
  259. const result: IPageWithMeta = await pageService.findPageAndMetaDataByViewer(pageId, currentPathname, user, true); // includeEmpty = true, isSharedPage = false
  260. const page = result?.data as unknown as PageDocument;
  261. // populate & check if the revision is latest
  262. if (page != null) {
  263. page.initLatestRevisionField(revisionId);
  264. await page.populateDataToShowRevision();
  265. props.isLatestRevision = page.isLatestRevision();
  266. }
  267. return result;
  268. }
  269. async function injectRoutingInformation(context: GetServerSidePropsContext, props: Props, pageWithMeta: IPageWithMeta|null): Promise<void> {
  270. const req: CrowiRequest = context.req as CrowiRequest;
  271. const { crowi } = req;
  272. const Page = crowi.model('Page') as PageModel;
  273. const { currentPathname } = props;
  274. const pageId = getPageIdFromPathname(currentPathname);
  275. const isPermalink = _isPermalink(currentPathname);
  276. const page = pageWithMeta?.data;
  277. if (props.isIdenticalPathPage) {
  278. // TBD
  279. }
  280. else if (page == null) {
  281. props.isNotFound = true;
  282. // check the page is forbidden or just does not exist.
  283. const count = isPermalink ? await Page.count({ _id: pageId }) : await Page.count({ path: currentPathname });
  284. props.isForbidden = count > 0;
  285. }
  286. else {
  287. // /62a88db47fed8b2d94f30000 ==> /path/to/page
  288. if (isPermalink && page.isEmpty) {
  289. props.currentPathname = page.path;
  290. }
  291. // /path/to/page ==> /62a88db47fed8b2d94f30000
  292. if (!isPermalink && !page.isEmpty) {
  293. const isToppage = pagePathUtils.isTopPage(props.currentPathname);
  294. if (!isToppage) {
  295. props.currentPathname = `/${page._id}`;
  296. }
  297. }
  298. }
  299. }
  300. // async function injectPageUserInformation(context: GetServerSidePropsContext, props: Props): Promise<void> {
  301. // const req: CrowiRequest = context.req as CrowiRequest;
  302. // const { crowi } = req;
  303. // const UserModel = crowi.model('User');
  304. // if (isUserPage(props.currentPagePath)) {
  305. // const user = await UserModel.findUserByUsername(UserModel.getUsernameByPath(props.currentPagePath));
  306. // if (user != null) {
  307. // props.pageUser = JSON.stringify(user.toObject());
  308. // }
  309. // }
  310. // }
  311. async function injectServerConfigurations(context: GetServerSidePropsContext, props: Props): Promise<void> {
  312. const req: CrowiRequest = context.req as CrowiRequest;
  313. const { crowi } = req;
  314. const {
  315. appService, searchService, configManager, aclService, slackNotificationService, mailService,
  316. } = crowi;
  317. props.isSearchServiceConfigured = searchService.isConfigured;
  318. props.isSearchServiceReachable = searchService.isReachable;
  319. props.isSearchScopeChildrenAsDefault = configManager.getConfig('crowi', 'customize:isSearchScopeChildrenAsDefault');
  320. props.isSlackConfigured = crowi.slackIntegrationService.isSlackConfigured;
  321. // props.isMailerSetup = mailService.isMailerSetup;
  322. props.isAclEnabled = aclService.isAclEnabled();
  323. // props.hasSlackConfig = slackNotificationService.hasSlackConfig();
  324. // props.drawioUri = configManager.getConfig('crowi', 'app:drawioUri');
  325. // props.hackmdUri = configManager.getConfig('crowi', 'app:hackmdUri');
  326. // props.mathJax = configManager.getConfig('crowi', 'app:mathJax');
  327. // props.noCdn = configManager.getConfig('crowi', 'app:noCdn');
  328. // props.highlightJsStyle = configManager.getConfig('crowi', 'customize:highlightJsStyle');
  329. // props.isAllReplyShown = configManager.getConfig('crowi', 'customize:isAllReplyShown');
  330. // props.isContainerFluid = configManager.getConfig('crowi', 'customize:isContainerFluid');
  331. props.isEnabledStaleNotification = configManager.getConfig('crowi', 'customize:isEnabledStaleNotification');
  332. // props.isEnabledLinebreaks = configManager.getConfig('markdown', 'markdown:isEnabledLinebreaks');
  333. // props.isEnabledLinebreaksInComments = configManager.getConfig('markdown', 'markdown:isEnabledLinebreaksInComments');
  334. // props.editorConfig = {
  335. // upload: {
  336. // image: crowi.fileUploadService.getIsUploadable(),
  337. // file: crowi.fileUploadService.getFileUploadEnabled(),
  338. // },
  339. // };
  340. // props.adminPreferredIndentSize = configManager.getConfig('markdown', 'markdown:adminPreferredIndentSize');
  341. // props.isIndentSizeForced = configManager.getConfig('markdown', 'markdown:isIndentSizeForced');
  342. props.sidebarConfig = {
  343. isSidebarDrawerMode: configManager.getConfig('crowi', 'customize:isSidebarDrawerMode'),
  344. isSidebarClosedAtDockMode: configManager.getConfig('crowi', 'customize:isSidebarClosedAtDockMode'),
  345. };
  346. }
  347. /**
  348. * for Server Side Translations
  349. * @param context
  350. * @param props
  351. * @param namespacesRequired
  352. */
  353. async function injectNextI18NextConfigurations(context: GetServerSidePropsContext, props: Props, namespacesRequired?: string[] | undefined): Promise<void> {
  354. const nextI18NextConfig = await getNextI18NextConfig(serverSideTranslations, context, namespacesRequired);
  355. props._nextI18Next = nextI18NextConfig._nextI18Next;
  356. }
  357. export const getServerSideProps: GetServerSideProps = async(context: GetServerSidePropsContext) => {
  358. const req: CrowiRequest = context.req as CrowiRequest;
  359. const { user } = req;
  360. const result = await getServerSideCommonProps(context);
  361. // check for presence
  362. // see: https://github.com/vercel/next.js/issues/19271#issuecomment-730006862
  363. if (!('props' in result)) {
  364. throw new Error('invalid getSSP result');
  365. }
  366. const props: Props = result.props as Props;
  367. let pageWithMeta;
  368. try {
  369. pageWithMeta = await getPageData(context, props);
  370. props.pageWithMetaStr = JSON.stringify(pageWithMeta);
  371. }
  372. catch (err) {
  373. if (err instanceof MultiplePagesHitsError) {
  374. props.isIdenticalPathPage = true;
  375. }
  376. else {
  377. throw err;
  378. }
  379. }
  380. injectRoutingInformation(context, props, pageWithMeta);
  381. injectServerConfigurations(context, props);
  382. injectNextI18NextConfigurations(context, props, ['translation']);
  383. if (user != null) {
  384. props.currentUser = JSON.stringify(user);
  385. }
  386. // UI
  387. const userUISettings = user == null ? null : await UserUISettings.findOne({ user: user._id }).exec();
  388. props.userUISettings = JSON.parse(JSON.stringify(userUISettings));
  389. return {
  390. props,
  391. };
  392. };
  393. export default GrowiPage;